package logic

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type RecommendPostLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRecommendPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RecommendPostLogic {
	return &RecommendPostLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RecommendPostLogic) RecommendPost(in *backend.RecommendPostReq) (*backend.RecommendPostResp, error) {
	items := strings.TrimSpace(in.Items)
	if len(items) == 0 {
		return nil, errorx.Status(errorx.ERROR_BLOG_POST_ID_REQUIRED, "")
	}

	parts := strings.Split(items, ";")
	if len(parts) > 0 {
		dateIdsMap := make(map[int][]string)
		var dates []interface{}
		for _, part := range parts {
			dateParts := strings.Split(part, ":")
			if len(dateParts) == 2 {
				idParts := strings.Split(dateParts[1], ",")
				if i, err := strconv.ParseInt(dateParts[0], 10, 32); err == nil {
					date := int(i)
					dates = append(dates, date)
					if len(idParts) > 0 {
						dateIdsMap[date] = idParts
					}
				}
			}
		}

		if len(dates) > 0 {
			filterMap := make(map[string]map[string][]interface{})
			filterMap[model.RecommendationColumns.StartDate] = map[string][]interface{}{
				"in": dates,
			}
			list, _, err := l.svcCtx.Recommendation.GetList(l.ctx, model.M{}, -1, filterMap)
			if err != nil {
				return nil, err
			}

			recMap := make(map[int]map[uint64]*model.Recommendation)
			if len(list) > 0 {
				for _, rec := range list {
					if _, exist := recMap[rec.StartDate]; !exist {
						recMap[rec.StartDate] = make(map[uint64]*model.Recommendation)
					}
					recMap[rec.StartDate][rec.EntryID] = rec
				}
			}

			var newRecs []*model.Recommendation
			now := time.Now() // 本地时间
			for date, ids := range dateIdsMap {
				if idMap, exist := recMap[date]; exist {
					for _, id := range ids {
						if i, err := strconv.ParseInt(id, 10, 64); err == nil {
							eid := uint64(i)
							if _, ok := idMap[eid]; ok {
								delete(idMap, eid) // 排除掉不需要删除的项
							} else {
								newRecs = append(newRecs, &model.Recommendation{
									EntryID:   eid,
									Type:      "brand",
									Status:    0,
									StartDate: date,
									EndDate:   date,
									CreatedAt: now,
									UpdatedAt: now,
								})
							}
						}
					}
				} else {
					for _, id := range ids {
						if i, err := strconv.ParseInt(id, 10, 64); err == nil {
							newRecs = append(newRecs, &model.Recommendation{
								EntryID:   uint64(i),
								Type:      "brand",
								Status:    0,
								StartDate: date,
								CreatedAt: now,
								UpdatedAt: now,
							})
						}
					}
				}
			}

			var delIds []uint64
			for _, idMap := range recMap {
				for _, rec := range idMap {
					delIds = append(delIds, rec.ID)
				}
			}

			logx.Infof("RecommendPost delIds : %+v ", delIds)

			_, err = l.svcCtx.Recommendation.UpdateByDate(l.ctx, newRecs, delIds)
			if err != nil {
				return nil, err
			}
		}
	}

	return &backend.RecommendPostResp{}, nil
}
